<?php

namespace app\api\lib;

use app\common\service\ConfigService;
use EasyWeChat\Factory;

class Wechat
{
    public static function config($type = 0)
    {
        $appWx = ConfigService::get('applet', 'app_wx');
        $appWx =  $appWx ? explode(',', $appWx) : [];
        $config = [
            'app_id' => $appWx[0] ?? '',
            'secret' => $appWx[1] ?? '',
            'mch_id' => $appWx[2] ?? '',
            'key' => $appWx[3] ?? '',
            'cert_path' => $appWx[4] ?? '',
            'key_path' => $appWx[5] ?? '',
        ];
        $data = ['code' => 1, 'config' => $config];
        if ($type == 1 && !$appWx[2]) {
            $data = ['code' => 0, 'msg' => '请先配置微信支付商户号！'];
        } else if ($type == 1 && !$appWx[3]) {
            $data = ['code' => 0, 'msg' => '请先配置微信支付KEY！'];
        } else if ($type == 2 && !$appWx[4]) {
            $data = ['code' => 0, 'msg' => '请先配置微信支付CERT证书！'];
        } else if ($type == 2 && !$appWx[5]) {
            $data = ['code' => 0, 'msg' => '请先配置微信支付KEY证书！'];
        }
        return $data;
    }

    public function pay($openid, $total_fee, $out_trade_no, $body)
    {
        $options = self::config(1);
        if ($options['code'] == 0) return $options;
        $options['config']['notify_url'] = request()->scheme() . '://' . request()->host() . "/api/notify/pay";
        $payment = Factory::payment($options['config']);
        $jssdk = $payment->jssdk;
        $attributes = [
            'trade_type' => 'JSAPI',                    // 支付方式，小程序支付使用JSAPI
            'body' => $body,                            // 订单说明
            'out_trade_no' => $out_trade_no,            // 自定义订单号
            'total_fee' => intval(floatval($total_fee) * 100),  // 单位：分
            'openid' => $openid                         // 当前用户的openId
        ];
        $result = $payment->order->unify($attributes);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id'];
            $config = $jssdk->sdkConfig($prepayId);
            return $config;
        }
        if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
            return $result;
        }
        return $result;
    }

    public static function refund($transaction_id, $out_refund_no, $total, $money, $reason = '')
    {
        $options = self::config(2);
        if ($options['code'] == 0) return $options;
        $options['config']['notify_url'] = request()->scheme() . '://' . request()->host() . "/api/notify/refund";
        $app = Factory::payment($options['config']);
        $transactionId = $transaction_id;             // 微信支付流水号
        $refundNumber = $out_refund_no;               // 订单号(和支付号二选一)
        $total = intval(floatval($total) * 100);              // 订单金额
        $refundMoney = intval(floatval($money) * 100);        // 退款金额
        $res = ['code' => 1];
        // 根据支付流水号退款，一笔付款可以分成多次退，但总退款金额不可超过支付时的金额
        $result = $app->refund->byTransactionId(
            $transactionId,
            $refundNumber,
            $total,
            $refundMoney,
            ['refund_desc' => $reason, 'notify_url' => $options['config']['notify_url']]
        );
        if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') {
            $res = ['code' => 0, 'msg' => $result['return_msg']];
        }
        return $res;
    }

    public function repay($out_trade_no)
    {
        $options = self::config();
        $options['config']['notify_url'] = request()->scheme() . '://' . request()->host() . "/api/notify/pay";
        $payment = Factory::payment($options['config']);
        $result = $payment->order->queryByOutTradeNumber($out_trade_no);
        return $result;
    }
}
